﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

namespace Asion.Dapper
{
    /// <summary>
    /// updae where
    /// </summary>
    public interface IUpdateWhere : ICondition
    {

    }


    public class UpdateWhere : BaseCondition, IUpdateWhere, IConditionDynamicParameters, IGetSql
    {
        private IEnumerable<string> where;

        public UpdateWhere(string[] str)
        {
            where = str;
        }

        public UpdateWhere(string str)
        {
            where = new string[] { str };
        }

        public IEnumerable<string> GetWhereColumns()
        {
            return where;
        }

        public override string BuildSql()
        {
            var result = string.Empty;
            if (where == null || !where.Any())
            {
                throw new Exception("sql must have where condition");
            }
            StringBuilder sql = new StringBuilder();
            int i = 0;
            foreach (var column in this.where)
            {
                if (i > 0)
                    sql.Append(" AND ");
                var mapping = _custom_table_mappinghandle.GetCustomTableMapping().GetColumnMapping(column);
                if (mapping == null)
                {
                    throw new ArgumentException($" column that {column} does not exist in where dic");
                }

                var formula = ComplexOperatorFactory.GetComplexCondtionOperatorFormula(CondtionOperator.Equals);
                //由于update where 适用于的范围是 实体类的参数 所以ColumnName也用实体名即可处理
                sql.AppendFormat(formula, _encap_sulation.EncapSulation(mapping.DataColumnName), _encap_sulation.EncapCloumnParam(mapping.ColumnName));
                // not param clean
                i++;
            }
            if (i > 0)
            {
                result = $" WHERE {sql.ToString()}";
            }
            return result;
        }

        public DynamicParameters GetDynamicParameters()
        {

            return DynamicParam;
        }
    }
}
